<template>
    <h1>上传</h1>

    <p>上传文件</p>
    <input type="file" accept="*/*" @change="handleFile" />
    <div v-if="file">
        <p>填写信息</p>
        <p>资源名称:{{ resource.resourceName }}</p>
        <UploadTypeSelector v-model="resource.resourceType" />
        <input type="text" v-model="resource.version" placeholder="版本号" />
        <input type="text" v-model="resource.customerName" placeholder="自定义命名" />
        <input type="text" v-model="resource.description" placeholder="简介" />
        <p>上传图片</p>
        <input type="file" multiple accept="image/*" @change="handleImages" />
        <div v-if="images.length > 0">
            <h2>预览图：</h2>
            <div v-for="(image, index) in imageUrls" :key="index">
                <button @click="removeImage(index)">×</button>
                <img :src="image" width="100" alt="Image Preview" />
            </div>
        </div>
        <button @click="upload">上传</button>
    </div>
</template>

<script lang="ts" setup>
import router from '@/router'
import { Resource } from '@/model/resource'
import { onMounted, ref } from 'vue'
import { reactive } from 'vue'
import UploadTypeSelector from '@/components/UploadTypeSelector.vue'
import { uploadRChunksAPI, uploadRInformationAPI, uploadRImagesAPI, jointRChunksAPI, clear } from '@/service/API'

const resource = reactive<Resource>({
    id: 0,
    resourceName: '',
    resourceType: 'document',
    resourceSize: '',
    version: '',
    customerName: '',
    updateTime: '',
    downloadCount: '',
    description: '',
    providerId: 0,
    providerName: ''
})
const file = ref<File | null>(null)
const images = ref<File[]>([])
const imageUrls = ref<string[]>([])





const handleFile = (event: Event) => {
    const target = event.target as HTMLInputElement
    if (!target.files || target.files.length === 0) return

    file.value = target.files[0]
    //console.log('文件名:', file.value?.name)               //调试
    if (file.value.name && resource) {
        resource.resourceName = file.value.name
        resource.resourceSize = (file.value.size / (1024 * 1024)).toFixed(2) + ' MB'
    }
}
const handleImages = (event: Event) => {
    const target = event.target as HTMLInputElement
    if (!target.files) return
    const selectedFiles = Array.from(target.files)
    images.value.push(...selectedFiles)
    target.value = ''
    selectedFiles.forEach(file => {
        const imageUrl = URL.createObjectURL(file)
        imageUrls.value.push(imageUrl) // 存储生成的 URL
    })
}
const removeImage = (index: number) => {
    images.value.splice(index, 1)
    imageUrls.value.splice(index, 1)
}



const uploadRImages = async (id: number)
    : Promise<{ R_uploadRImages: boolean }> => {
    // 检查是否有图片文件
    if (!(images.value.length > 0)) {
        console.log("图片获取数量为零");
        return { R_uploadRImages: true }
    }
    // 创建 FormData 对象并附加资源 ID 和图片文件
    const formDataImage = new FormData();
    formDataImage.append('resourceId', id.toString());
    for (let i = 0; i < images.value.length; i++) {
        formDataImage.append('images', images.value[i]);  // 注意：append 多个同名字段
    }
    const { R_uploadRImagesAPI } = await uploadRImagesAPI(id, formDataImage)
    return { R_uploadRImages: R_uploadRImagesAPI }
}

const uploadRChunks = async (id: number)
    : Promise<{ R_uploadRChunks: boolean, totalChunks: number }> => {
    if (!file.value) {
        console.log('块上传未获得原始文件');
        return { R_uploadRChunks: false, totalChunks: 0 };
    }

    // 设置每块的大小
    const chunkSize = 1 * 1024 * 1024; // 每块1MB
    const totalChunks = Math.ceil(file.value.size / chunkSize);
    let reupload = 0;

    for (let currentChunkIndex = 0; currentChunkIndex < totalChunks;) {
        const start = currentChunkIndex * chunkSize;
        const end = Math.min(file.value.size, start + chunkSize);
        const chunk = file.value.slice(start, end);

        const formDataChunk = new FormData();
        formDataChunk.append('resourceId', id.toString());
        formDataChunk.append('file', chunk);
        formDataChunk.append('index', currentChunkIndex.toString());
        formDataChunk.append('totalChunks', totalChunks.toString());

        const { R_uploadRChunksAPI } = await uploadRChunksAPI(formDataChunk, currentChunkIndex)
        if (!R_uploadRChunksAPI) {
            reupload++;
        } else {
            currentChunkIndex++
            reupload = 0;
        }
        if (reupload >= 3) {
            return { R_uploadRChunks: false, totalChunks: 0 };
        }
    }
    return { R_uploadRChunks: true, totalChunks: totalChunks };
}


const upload = async () => {
    if (file.value) {
        const { R_uploadRInformationAPI, id } = await uploadRInformationAPI(resource)
        if (R_uploadRInformationAPI) {
            let success21 = true
            if (images.value.length > 0) {
                const { R_uploadRImages } = await uploadRImages(id)
                success21 = R_uploadRImages
            }
            if (success21) {
                const { R_uploadRChunks, totalChunks } = await uploadRChunks(id)
                if (R_uploadRChunks) {
                    const { R_jointRChunksAPI } = await jointRChunksAPI(id, file.value.name, totalChunks)
                    if (R_jointRChunksAPI) {
                        console.log('合并请求成功');
                        alert('上传成功');
                        window.location.reload()
                    }
                } else {
                    console.log('文件信息上传失败');
                    clear(id)
                }
            } else {
                console.log('图片信息上传失败');
                clear(id)
            }

        } else {
            console.log('数据信息上传失败');
            clear(id)
        }

    }

}


onMounted(() => {
    const token = localStorage.getItem('token');
    if (!token) {
        alert('上传功能需要登陆')
        router.push('/login')
    }
})
</script>

<style scoped></style>